package calc

import "errors"

//Sum 求和
func Sum(args ...interface{}) (interface{}, error) {
	sum := float64(0)
	for i := range args {
		val, err := Float64(args[i])
		if err == nil {
			sum += val
		}
	}
	return float64(sum), nil
}

//Avg 平均值
func Avg(args ...interface{}) (interface{}, error) {
	count := 0
	avg := float64(0)
	sum := float64(0)
	for i := range args {
		val, err := Float64(args[i])
		if err == nil {
			sum += val
			count++
		}
	}

	if count == 0 {
		return avg, nil
	}
	avg = sum / float64(count)
	return avg, nil

}

//Max 最大值
func Max(args ...interface{}) (interface{}, error) {
	if len(args) == 0 {
		return nil, errors.New("Max 至少需要一个参数")
	}
	ok := false
	max := float64(0)
	for i := range args {
		val, err := Float64(args[i])
		if err != nil {
			continue
		}
		if !ok {
			max = val
			ok = true
			continue
		}
		if max < val {
			max = val
		}
	}
	return max, nil
}

//Min 最小值
func Min(args ...interface{}) (interface{}, error) {
	if len(args) == 0 {
		return nil, errors.New("Max 至少需要一个参数")
	}
	ok := false
	min := float64(0)
	for i := range args {
		val, err := Float64(args[i])
		if err != nil {
			continue
		}
		if !ok {
			min = val
			ok = true
			continue
		}
		if min < val {
			min = val
		}
	}
	return min, nil
}
